const proxiedMap = new WeakMap()

export default function proxyData(data, parentPath = '') {
  if (!isObj(data)) return data

  if (proxiedMap.has(data)) {
    return proxiedMap.get(data)
  }

  const handle = {
    get: (target, prop) => {
      console.log('获取', prop)
      return target[prop]
    },

    set: (target, prop, value) => {
      if (target[prop] !== value) {
        console.log('修改', prop)
        
        if (isObj(value)) {
          value = proxyData.call(this, value)
        }
        target[prop] = value
      }
      return true
    }
  }

  for (let prop in data) {
    if (Object.hasOwn(data, prop)) {
      if (isObj(data[prop])) {
        data[prop] = proxyData.call(this, data[prop])
      }
    }
  }

  const proxy = new Proxy(data, handle)

  proxiedMap.set(data, proxy)

  return proxy
}

function isObj(target) {
  return (typeof target === 'object' && target !== null)
}
